﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Net;
using System.Drawing;
using System.IO;


using RGPWEB.cn.com.webxml;
using System.Data;
using Microsoft.VisualBasic;
using System.Web.Caching;

namespace RGPWEB
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            //System.IO.StreamReader reader = new System.IO.StreamReader(Request.InputStream);
            //String xml = reader.ReadToEnd();

            //if (Request.RequestType == "POST")
            //{ 
            //}

            string FromUserName = "";
            string ToUserName = "";
            string Content = "";
            string CreateTime = "";
            string MsgType = "";
            string MsgId = "";
            string Location_X = "";
            string Location_Y = "";
            string Scale = "";
            string Label = "";
            string PicUrl = "";

            //WeatherS("厦门市");

            System.Xml.XmlDocument dom = new System.Xml.XmlDocument();
            try
            {
                dom.Load(Request.InputStream);//加载Post过来的XML

                System.Xml.XmlNode node = dom.SelectSingleNode("//FromUserName");
                if (node != null)
                {
                    //WriteNote("FromUserName=" + node.InnerText);  //记录ToUserName节点的值
                    FromUserName = node.InnerText;

                    dom.Save(Server.MapPath(".") + "\\data.xml");  //保存post过来的xml文件到本地data.xml

                    //Response.Write("nodeValue=" + node.InnerText);
                }

                node = dom.SelectSingleNode("//ToUserName");
                if (node != null)
                {
                    ToUserName = node.InnerText;
                }


                node = dom.SelectSingleNode("//CreateTime");
                if (node != null)
                {
                    CreateTime = node.InnerText;
                }

                node = dom.SelectSingleNode("//MsgType");
                if (node != null)
                {
                    MsgType = node.InnerText;
                }

                node = dom.SelectSingleNode("//MsgId");
                if (node != null)
                {
                    MsgId = node.InnerText;
                }

                WriteNote("FromUserName=" + FromUserName);
                WriteNote("ToUserName=" + ToUserName);
                WriteNote("CreateTime=" + CreateTime);
                WriteNote("MsgType=" + MsgType);
                WriteNote("MsgId=" + MsgId);

                #region 文本消息结构
                if (MsgType.ToLower() == "text") //返回的是文本消息xml格式
                {
                    //ToUserName 消息接收方微信号，一般为公众平台账号微信号 
                    //FromUserName 消息发送方微信号 
                    //CreateTime 消息创建时间 
                    //MsgType 文本消息为text 
                    //Content 消息内容

                    node = dom.SelectSingleNode("//Content"); //取得消息内容
                    if (node != null)
                    {
                        Content = node.InnerText;
                        WriteNote("Content=" + Content);
                    }

                    if (Content == "p")     //回复图文消息
                    {
                        string strresponse = "";
                        strresponse = "<xml>";
                        strresponse = strresponse + "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>";
                        strresponse = strresponse + "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>";
                        strresponse = strresponse + "<CreateTime>" + CreateTime + "</CreateTime>";
                        strresponse = strresponse + "<MsgType><![CDATA[news]]></MsgType>";
                        strresponse = strresponse + "<Content><![CDATA[test1]]></Content>";
                        strresponse = strresponse + "<ArticleCount>2</ArticleCount>";
                        strresponse = strresponse + "<Articles>";
                        strresponse = strresponse + "<item>";
                        strresponse = strresponse + "<Title><![CDATA[美女推荐111]]></Title>";
                        strresponse = strresponse + "<Description><![CDATA[111希望找一个成熟稳重一点的男士做朋友]]></Description>";
                        strresponse = strresponse + "<PicUrl><![CDATA[http://weixin.lie8.com/test.jpg]]></PicUrl>";
                        strresponse = strresponse + "<Url><![CDATA[http://weixin.lie8.com/test111.html]]></Url>";
                        strresponse = strresponse + "</item>";
                        strresponse = strresponse + "<item>";
                        strresponse = strresponse + "<Title><![CDATA[美女推荐222]]></Title>";
                        strresponse = strresponse + "<Description><![CDATA[222希望找一个成熟稳重一点的男士做朋友]]></Description>";
                        strresponse = strresponse + "<PicUrl><![CDATA[http://weixin.lie8.com/test.jpg]]></PicUrl>";
                        strresponse = strresponse + "<Url><![CDATA[http://weixin.lie8.com/test222.html]]></Url>";
                        strresponse = strresponse + "</item>";
                        strresponse = strresponse + "</Articles>";
                        strresponse = strresponse + "<FuncFlag>0</FuncFlag>";
                        strresponse = strresponse + "</xml>";


                        WriteNote(strresponse);

                        Response.Write(strresponse);

                        //filepath=server.mappath(".")&"\wx.txt"
                        //Set fso = Server.CreateObject("Scripting.FileSystemObject")
                        //set fopen=fso.OpenTextFile(filepath, 8 ,true)
                        //fopen.writeline(strresponse)
                        //fopen.writeline("-----")
                        //set fso=nothing
                        //set fopen=Nothing

                        //   response.write strresponse
                    }

                    string[] weatherArray= WeatherS(Content);
                    if (weatherArray[0] != "查询结果为空！")     //回复图文消息
                    {
                        string strresponse = "";
                        strresponse = "<xml>";
                        strresponse = strresponse + "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>";
                        strresponse = strresponse + "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>";
                        strresponse = strresponse + "<CreateTime>" + CreateTime + "</CreateTime>";
                        strresponse = strresponse + "<MsgType><![CDATA[news]]></MsgType>";
                        strresponse = strresponse + "<Content><![CDATA[test1]]></Content>";
                        strresponse = strresponse + "<ArticleCount>3</ArticleCount>";
                        strresponse = strresponse + "<Articles>";
                        strresponse = strresponse + "<item>";
                        strresponse = strresponse + "<Title><![CDATA[" + weatherArray[6] + "," + weatherArray[5] + "]]></Title>";
                        strresponse = strresponse + "<Description><![CDATA[" + weatherArray[10] + "]]></Description>";
                        strresponse = strresponse + "<PicUrl><![CDATA[http://weixin.lie8.com/images/weather/" + weatherArray[8] + "]]></PicUrl>";
                        strresponse = strresponse + "<Url><![CDATA[http://weixin.lie8.com/test111.html]]></Url>";
                        strresponse = strresponse + "</item>";
                        strresponse = strresponse + "<item>";
                        strresponse = strresponse + "<Title><![CDATA[" + weatherArray[13] + "," + weatherArray[12] + "]]></Title>";
                        strresponse = strresponse + "<Description><![CDATA[" + weatherArray[14] + "]]></Description>";
                        strresponse = strresponse + "<PicUrl><![CDATA[http://weixin.lie8.com/images/weather/" + weatherArray[15] + "]]></PicUrl>";
                        strresponse = strresponse + "<Url><![CDATA[http://weixin.lie8.com/test222.html]]></Url>";
                        strresponse = strresponse + "</item>";
                        strresponse = strresponse + "<item>";
                        strresponse = strresponse + "<Title><![CDATA[" + weatherArray[18] + "," + weatherArray[17] + "]]></Title>";
                        strresponse = strresponse + "<Description><![CDATA[" + weatherArray[19] + "]]></Description>";
                        strresponse = strresponse + "<PicUrl><![CDATA[http://weixin.lie8.com/images/weather/" + weatherArray[20] + "]]></PicUrl>";
                        strresponse = strresponse + "<Url><![CDATA[http://weixin.lie8.com/test222.html]]></Url>";
                        strresponse = strresponse + "</item>";
                        strresponse = strresponse + "</Articles>";
                        strresponse = strresponse + "<FuncFlag>0</FuncFlag>";
                        strresponse = strresponse + "</xml>";


                        WriteNote(strresponse);

                        Response.Write(strresponse);

                        //filepath=server.mappath(".")&"\wx.txt"
                        //Set fso = Server.CreateObject("Scripting.FileSystemObject")
                        //set fopen=fso.OpenTextFile(filepath, 8 ,true)
                        //fopen.writeline(strresponse)
                        //fopen.writeline("-----")
                        //set fso=nothing
                        //set fopen=Nothing

                        //   response.write strresponse
                    }
                }
                #endregion

                #region 地理位置消息结构
                if (MsgType.ToLower() == "location") //返回的是地理位置消息xml格式
                {
                    //ToUserName 消息接收方微信号，一般为公众平台账号微信号 
                    //FromUserName 消息发送方微信号 
                    //CreateTime 消息创建时间 
                    //MsgType 消息类型，地理位置为location 
                    //Location_X 地理位置纬度 
                    //Location_Y 地理位置经度 
                    //Scale 地图缩放大小 
                    //Label 地理位置信息

                    node = dom.SelectSingleNode("//Location_X"); //取得 地理位置纬度
                    if (node != null)
                    {
                        Location_X = node.InnerText;
                        WriteNote("Location_X=" + Location_X);
                    }
                    node = dom.SelectSingleNode("//Location_Y"); //取得 地理位置经度
                    if (node != null)
                    {
                        Location_Y = node.InnerText;
                        WriteNote("Location_Y=" + Location_Y);
                    }
                    node = dom.SelectSingleNode("//Scale"); //取得 地图缩放大小
                    if (node != null)
                    {
                        Scale = node.InnerText;
                        WriteNote("Scale=" + Scale);
                    }
                    node = dom.SelectSingleNode("//Label"); //取得 地理位置信息
                    if (node != null)
                    {
                        Label = node.InnerText;
                        WriteNote("Label=" + Label);
                    }

                    //回复消息提示用户所发地图已收到
                    string strresponse = "";
                    strresponse = "<xml>";
                    strresponse = strresponse + "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>";
                    strresponse = strresponse + "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>";
                    strresponse = strresponse + "<CreateTime>" + CreateTime + "</CreateTime>";
                    strresponse = strresponse + "<MsgType><![CDATA[text]]></MsgType>";
                    strresponse = strresponse + "<Content><![CDATA[您发送的地理位置已收到，" + Label + "：" + Location_X + "," + Location_Y + "，缩放大小为：" + Scale + "]]></Content>";
                    strresponse = strresponse + "<FuncFlag>0</FuncFlag>";
                    strresponse = strresponse + "</xml>";
                    WriteNote(strresponse);
                    Response.Write(strresponse);

                }
                #endregion

                #region 图片消息结构
                if (MsgType.ToLower() == "image") //返回的是图片消息结构
                {
                    //ToUserName 消息接收方微信号，一般为公众平台账号微信号 
                    //FromUserName 消息发送方微信号 
                    //CreateTime 消息创建时间 
                    //MsgType 消息类型image 
                    //PicUrl 图片链接，开发者可以用HTTP GET获取

                    node = dom.SelectSingleNode("//PicUrl"); //取得 图片链接
                    if (node != null)
                    {
                        PicUrl = node.InnerText;
                        WriteNote("PicUrl=" + PicUrl);
                    }

                    //把图片保存到本地
                    string sFile = PicUrl;
                    string imgUrl = PicUrl;
                    if (!string.IsNullOrEmpty(imgUrl))
                    {
                        Uri myUri = new Uri(imgUrl);
                        WebRequest webRequest = WebRequest.Create(myUri);
                        WebResponse webResponse = webRequest.GetResponse();
                        Bitmap myImage = new Bitmap(webResponse.GetResponseStream());
                        //MemoryStream ms = new MemoryStream();
                        //myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        sFile = "" + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0')
                            + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0')
                            + MsgId + ".jpg";
                        myImage.Save(Server.MapPath("~/images/") + sFile,
                            System.Drawing.Imaging.ImageFormat.Jpeg);
                        WriteNote("DateTime.Now.Month.ToString().PadLeft(2, '0')" + DateTime.Now.Month.ToString().PadLeft(2, '0'));
                        WriteNote("DateTime.Now.Day.ToString().PadLeft(2, '0')" + DateTime.Now.Day.ToString().PadLeft(2, '0'));
                        WriteNote("sFile=" + sFile);

                        //context.Response.ClearContent();
                        //context.Response.ContentType = "image/Jpeg";
                        //context.Response.BinaryWrite(ms.ToArray());
                    }


                    //回复消息提示用户所发图片已收到
                    string strresponse = "";
                    strresponse = "<xml>";
                    strresponse = strresponse + "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>";
                    strresponse = strresponse + "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>";
                    strresponse = strresponse + "<CreateTime>" + CreateTime + "</CreateTime>";
                    strresponse = strresponse + "<MsgType><![CDATA[text]]></MsgType>";
                    strresponse = strresponse + "<Content><![CDATA[您发送的图片已收到，地址是：http://weixin.lie8.com/images/" + sFile + "]]></Content>";
                    strresponse = strresponse + "<FuncFlag>0</FuncFlag>";
                    strresponse = strresponse + "</xml>";
                    WriteNote(strresponse);
                    Response.Write(strresponse);

                }
                #endregion
            }
            catch (Exception ex)
            {
                WriteNote("发生错误!");
                WriteNote(ex.Message);
                WriteNote(ex.Source);
                WriteNote(ex.HelpLink);
                //Response.Write("发生错误!");
            }

            //文本消息xml格式
            //<xml>
            //<ToUserName><![CDATA[toUser]]></ToUserName>
            //<FromUserName><![CDATA[fromUser]]></FromUserName>
            //<CreateTime>1348831860</CreateTime>
            //<MsgType><![CDATA[text]]></MsgType>
            //<Content><![CDATA[this is a test]]></Content>
            //</xml> 


            Response.End();  //向页面输出所有缓冲
        }

        void WriteNote(string str)
        {
            System.IO.StreamWriter sw = System.IO.File.AppendText(Server.MapPath(".") + "\\log.txt");
            sw.WriteLine(System.DateTime.Now.ToString());
            sw.WriteLine(str);
            sw.Flush();
            sw.Close();
        }

        string[] WeatherS(string cityname)
        {
            WeatherWebService wws = new WeatherWebService();
            cityname = cityname.TrimEnd('省').TrimEnd('市').TrimEnd('县').TrimEnd('区');

            string[] weatherArray = wws.getWeatherbyCityName(cityname);


            //Console.WriteLine("{0}-{1}-{2}", weatherArray[6], weatherArray[7], weatherArray[8]);
            //Console.Read();

            return weatherArray;
        }

        //public static DataSet getDataSet() {

        //           WeatherWebService  weather = new WeatherWebService();
        //           ds = weather.getSupportDataSet();
        //           HttpContext.Current.Cache.Insert("dataSetCache", ds, null, DateTime.Now.AddHours(12),TimeSpan.Zero, CacheItemPriority.High, null) //添加Cache缓存数据提高速度;

        //       return ds;
        //   }

        //public static string[] getCityWeather( string  cityCode) {
        //        string  cacheName = "weather" + cityCode.Trim();
        //        string[] weatherArray= HttpContext.Current.Cache(cacheName);
        //       if ( weatherArray == null ) {
        //           WeatherWebService weather = new WeatherWebService();
        //           weatherArray = weather.getWeatherbyCityName(cityCode);
        //           HttpContext.Current.Cache.Insert(cacheName, weatherArray, null, DateTime.Now.AddMinutes(90), TimeSpan.Zero, CacheItemPriority.High, null) //添加Cache缓存数据提高速度;
        //       }
        //       return weatherArray;
        //   }


        //    }
    }
}

